const fs = require('fs');
const path = require('path');
const { STS } = require('ali-oss');
const configs = require('./config');

module.exports = async function aliyunOss() {
  let policy;
  if (configs.PolicyFile) {
    policy = fs.readFileSync(path.resolve(__dirname, configs.PolicyFile)).toString('utf-8');
  }
  // 角色可以没有权限，但是用户必须要有“调用STS服务AssumeRole接口的权限”的权限
  const client = new STS({
    accessKeyId: configs.AccessKeyId,
    accessKeySecret: configs.AccessKeySecret
  });
  try {
    const result = await client
      .assumeRole(configs.RoleArn, policy, configs.TokenExpireTime);
    return {
      AccessKeyId: result.credentials.AccessKeyId,
      AccessKeySecret: result.credentials.AccessKeySecret,
      SecurityToken: result.credentials.SecurityToken,
      Expiration: result.credentials.Expiration
    }
  } catch (error) {
    return error.message;
  }
};
